import Vue from 'vue';
import VueRouter from 'vue-router';
import {routers} from './router';
import iView from 'iview';
import Util from '@/lib/util';
import Cookies from 'js-cookie'
import { appRouters,otherRouters} from './router'

Vue.use(VueRouter);

const RouterConfig = {
    // mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);

    if (!Util.abp.session.userId&& to.name !== 'login') {
        next({
            name: 'login'
        });
    } else if (!!Util.abp.session.userId && to.name === 'login') {
        Util.title(to.meta.title);
        next({
            name: 'home'
        });
    } else {
        const curRouterObj = Util.getRouterObjByName([otherRouters, ...appRouters], to.name);
        // if (curRouterObj && curRouterObj.permission) {
        // undefined means need NOT ANY permissions (except [error-403])
        if (curRouterObj && typeof curRouterObj.permission !== 'undefined') {
            if (Util.abp.auth.hasPermission(curRouterObj.permission)) {
                Util.toDefaultPage([otherRouters, ...appRouters], to.name, router, next);
            } else {
                next({
                    replace: true,
                    name: 'error-403'
                });
            }
        } else {
            Util.toDefaultPage([...routers], to.name, router, next);
        }
    }
});
router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});